package com.woniuxy.juc.reentrant;

import com.woniuxy.untis.Sleep;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 线程间的消息队列
 * <P> Date: 2022/4/7:17:40
 * <P> Description:
 */
@Slf4j(topic = "c.Test23")
public class Test23 {
    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("1");
        Chopstick c2 = new Chopstick("2");
        Chopstick c3 = new Chopstick("3");
        Chopstick c4 = new Chopstick("4");
        Chopstick c5 = new Chopstick("5");
        new Philosopher("t1", c1, c2).start();
        new Philosopher("t2", c2, c3).start();
        new Philosopher("t3", c3, c4).start();
        new Philosopher("t4", c4, c5).start();
        new Philosopher("t5", c5, c1).start();
    }
}


@Slf4j(topic = "c.Philosopher")
class Philosopher extends Thread {
    Chopstick left;
    Chopstick right;

    public Philosopher(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }
    private void eat() {
        log.debug("eating...");
        Sleep.sleep(500);
    }



    @Override
    public void run() {
        while (true) {
            // 获得左手筷子
            if (left.tryLock()) {

                try {
                    // 获得右手筷子
                    if (right.tryLock()) {
                        try {
                            // 吃饭
                            eat();
                        } finally {
                            right.unlock();
                        }
                    }
                } finally {
                    left.unlock();
                }
            }


        }


    }
}

@Slf4j(topic = "c.Chopstick")
class Chopstick extends ReentrantLock {
    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" + name + '}';
    }
}

